package com.itheima.store.controller;


import com.itheima.store.common.ProductConst;
import com.itheima.store.entity.Product;
import com.itheima.store.service.ProductService;
import com.itheima.store.utils.Result;
import com.itheima.store.utils.UUIDUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ProductUploadController {

    @Autowired
    ProductService productService;

    @RequestMapping("productUpload")
    public Result productUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 1.获取表单数据
        Map<String, String[]> map = getMap(request);
        System.out.println(map         );
        // 2.封装到Bean对象
        Product product = new Product();
        BeanUtils.populate(product, map);

        // 3.初始化Prodcut对象
        // 设置UUID
        product.setPid(UUIDUtils.getUUID());
        // 设置是否上架
        product.setPflag(ProductConst.PFLAG);
        // 设置日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String createDate = sdf.format(new Date());
        product.setPdate(createDate);
        // 4.调用业务层完成添加商品
        System.out.println(product);
        if(productService.addProduct(product)){
                return new Result(Result.SUCCESS,"添加成功");
        }
        return new Result(Result.FAILS, "添加失败");


    }

    public Map<String, String[]> getMap(HttpServletRequest request) {
        Map<String, String[]> map = new HashMap<String, String[]>();
        try {
            //创建磁盘工厂对象
            DiskFileItemFactory itemFactory = new DiskFileItemFactory();
            //创建Servlet的上传解析对象,构造方法中,传递磁盘工厂对象
            ServletFileUpload fileUpload = new ServletFileUpload(itemFactory);
            /*
             * fileUpload调用方法 parseRequest,解析request对象
             * 页面可能提交很多内容 文本框,文件,菜单,复选框 是为FileItem对象
             * 返回集合,存储的文件项对象
             */
            List<FileItem> list = fileUpload.parseRequest(request);
            for (FileItem item : list) {
                //判断普通项还是附件项
                if (item.isFormField()) {
                    //取出普通项的name属性值  name="username"
                    String name = item.getFieldName();
                    //取出普通的填写的值
                    String value = item.getString("utf-8");
                    map.put(name, new String[]{value});
                } else {
                    // 附件项
                    // 获取上传的文件名   Lighthouse.jpg
                    //String fileName = item.getName();
                    // 对文件名进行重命名,采用UUID+"_"+文件名
                    String fileName = UUIDUtils.getUUID().replace("-", "") + "_" + item.getName();
                    // 读取文件数据，并存到磁盘
                    //String uploadDir = "D:\\idea_project\\itheima_shop\\web\\resources\\products";
                    String uploadDir = "E:\\JavaProject-IDEA\\SSMshixun\\web\\resources\\products";
                    // 构建本地存储的文件对象
                    File uploadFile = new File(uploadDir, fileName);

                    // 从上传文件项获取字节输入流，然后写前端资源路径下
                    InputStream inputStream = item.getInputStream();
                    FileOutputStream fos = new FileOutputStream(uploadFile);
                    // 通过IO工具存入磁盘
                    IOUtils.copy(inputStream, fos);

                    // 存入数据库的路径，是从resources目录开始的相对路径
                    String path = uploadFile.getAbsolutePath();
                    String saveDbPath = path.substring(path.indexOf("resources"));
                    map.put("pimage", new String[]{saveDbPath});

                    // 关闭流
                    IOUtils.closeQuietly(fos);
                    IOUtils.closeQuietly(inputStream);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return map;
    }
}
